
var board = new Array();
var score = 0;
var hasConflicted = new Array();




$(document).ready(function(){
	
    newgame();
});

function newgame(){
	 console.log(score);
	
    //初始化棋盘格
    init();
    //在随机两个格子生成数字
    generateOneNumber();
    generateOneNumber();
   
}

function init(){
	  score = 0 ;
	  updateScore(score);
	 //i表示4*4的格子中的行
    for( var i = 0 ; i < 4 ; i ++ )
    //j表示4*4格子中的列
        for( var j = 0 ; j < 4 ; j ++ ){
			//双重遍历获取每个格子元素
            var gridCell = $('#grid-cell-'+i+"-"+j);
            //获取格子距顶端、左端的距离
            gridCell.css('top', getPosTop( i , j ) );
            gridCell.css('left', getPosLeft( i , j ) );
        }

    for( var i = 0 ; i < 4 ; i ++ ){
        board[i] = new Array();
        hasConflicted[i] = new Array();
        for( var j = 0 ; j < 4 ; j ++ ){
        	//初始化格子的值
            board[i][j] = 0;
            hasConflicted[i] [j] = false;
            
        }
    }

    updateBoardView();
    
  
}

function updateBoardView(){
	//先清空之前的数字格子
    $(".number-cell").remove();
    for( var i = 0 ; i < 4 ; i ++ )
        for( var j = 0 ; j < 4 ; j ++ ){
        	//向棋盘格子上增加数字
            $("#grid-container").append( '<div class="number-cell" id="number-cell-'+i+'-'+j+'"></div>' );
            var theNumberCell = $('#number-cell-'+i+'-'+j);
			
			//棋盘格值为0，则设置数字格高宽都为0.
            if( board[i][j] == 0 ){
                theNumberCell.css('width','0px');
                theNumberCell.css('height','0px');
                theNumberCell.css('top',getPosTop(i,j) + 50 );
                theNumberCell.css('left',getPosLeft(i,j) + 50 );
            }
            //棋盘格不为0，则设置数字格高宽为100，且设置颜色。
            else{
                theNumberCell.css('width','100px');
                theNumberCell.css('height','100px');
                theNumberCell.css('top',getPosTop(i,j));
                theNumberCell.css('left',getPosLeft(i,j));
                theNumberCell.css('background-color',getNumberBackGroundColor( board[i][j] ) );
                theNumberCell.css('color',getNumberColor( board[i][j] ) );
                theNumberCell.text( board[i][j] );
            }
            hasConflicted[i][j] =  false;
        }
}

function generateOneNumber(){

    if( nospace( board ) )
        return false;

    //随机一个位置
    var randx = parseInt( Math.floor( Math.random()  * 4 ) );
    var randy = parseInt( Math.floor( Math.random()  * 4 ) );
	//随机生成空格子
	var times = 0;
    while( times < 50 ){
        if( board[randx][randy] == 0 )
            break;
		
		//重新随机一个位置
        randx = parseInt( Math.floor( Math.random()  * 4 ) );
        randy = parseInt( Math.floor( Math.random()  * 4 ) );
        
        times ++;
    }
    if(times ==50){
    	for (var i = 0; i< 4; i++) {
    		for (var j = 0; j < 4; j++) {
    			if(board[i][j] ==0){
    				randx = i;
    				randy = j;
    			}
    		}
    	}
    }

    //随机一个数字
    var randNumber = Math.random() < 0.5 ? 2 : 4;

    //在随机位置显示随机数字
    board[randx][randy] = randNumber;
    //实现随机数字显示动画
    showNumberWithAnimation( randx , randy , randNumber );

    return true;
}

$(document).keydown( function( event ){
    switch( event.keyCode ){
        case 37: //left
            if( moveLeft() ){
                setTimeout("generateOneNumber()",210);
                setTimeout("isgameover()",300);
            }
            break;
        case 38: //up
            if( moveUp() ){
                setTimeout("generateOneNumber()",210);
                setTimeout("isgameover()",300);
            }
            break;
        case 39: //right
            if( moveRight() ){
                setTimeout("generateOneNumber()",210);
                setTimeout("isgameover()",300);
            }
            break;
        case 40: //down
            if( moveDown() ){
                setTimeout("generateOneNumber()",210);
                setTimeout("isgameover()",300);
            }
            break;
        default: //default
            break;
    }
});

function isgameover(){
	if(nospace(board) && nomove(board)){
		gameover();
	}
}

function gameover(){
	alert("gameover!!!");
}

//function  gameover(){
//	$("#grid-container").append("<div id='gameover' class='gameover'><p>本次得分</p><span>"+score+"</span><a href='javascript:restartgame();' id='restartgamebutton'>Restart</a></div>");
//	var gameover = $("#gameover");
//	gameover.css("width","500px");
//	gameover.css("height","500px");
//	gameover.css("background-color","rgba(0,0,0,0.5)");
//	
//}
//
//function restartgame(){
//	$("#gameover").remove();
//	updateScore(score);	
//	newgame();
//}

function moveLeft(){

    if( !canMoveLeft( board ) )
        return false;

    //moveLeft
    for( var i = 0 ; i < 4 ; i ++ )
        for( var j = 1 ; j < 4 ; j ++ ){
            if( board[i][j] != 0 ){

                for( var k = 0 ; k < j ; k ++ ){
                	//判断当前值不为0的数字格左边的数字格必须值是0，且中间的数字格的值必须为0。（其他方向同理）
                    if( board[i][k] == 0 && noBlockHorizontal( i , k , j , board ) ){
                        //移动
                        showMoveAnimation( i , j , i , k );
                        board[i][k] = board[i][j];
                        board[i][j] = 0;
                        continue;
                    }
                    //判断当前值不为0的数字格和左边的数字格的值必须相等，且中间的数字格的值必须为0。（其他方向同理）
                    else if( board[i][k] == board[i][j] && noBlockHorizontal( i , k , j , board ) && !hasConflicted[i][k] ){
                        //移动
                        showMoveAnimation( i , j , i , k );
                        //增加
                        board[i][k] += board[i][j];
                        board[i][j] = 0;
						//分数增加
						score += board[i][k];
						updateScore(score); 
						hasConflicted[i][k]  = true;
						
                        continue;
                    }
                }
            }
        }

    setTimeout("updateBoardView()",200);
    return true;
}

function moveRight(){
    if( !canMoveRight( board ) )
        return false;

    //moveRight
    for( var i = 0 ; i < 4 ; i ++ )
        for( var j = 2 ; j >= 0 ; j -- ){
            if( board[i][j] != 0 ){
                for( var k = 3 ; k > j ; k -- ){

                    if( board[i][k] == 0 && noBlockHorizontal( i , j , k , board ) ){
                        //移动
                        showMoveAnimation( i , j , i , k );
                        board[i][k] = board[i][j];
                        board[i][j] = 0;
                        continue;
                    }
                    else if( board[i][k] == board[i][j] && noBlockHorizontal( i , j , k , board ) && !hasConflicted[i][k]){
                        //移动
                        showMoveAnimation( i , j , k , j );
                        //增加
                        board[i][k] += board[i][j];
                        board[i][j] = 0;
						//分数增加
						score += board[i][k];
						updateScore(score); 
						hasConflicted[i][k]  = true;
						
                        continue;
                    }
                }
            }
        }

    setTimeout("updateBoardView()",200);
    return true;
}

function moveUp(){

    if( !canMoveUp( board ) )
        return false;

    //moveUp
    for( var j = 0 ; j < 4 ; j ++ )
        for( var i = 1 ; i < 4 ; i ++ ){
            if( board[i][j] != 0 ){
                for( var k = 0 ; k < i ; k ++ ){

                    if( board[k][j] == 0 && noBlockVertical( j , k , i , board ) ){
                        //移动
                        showMoveAnimation( i , j , k , j );
                        board[k][j] = board[i][j];
                        board[i][j] = 0;
                        continue;
                    }
                    else if( board[k][j] == board[i][j] && noBlockVertical( j , k , i , board ) && !hasConflicted[k][j]){
                      	//移动
                        showMoveAnimation( i , j , k , j );
                        //增加
                        board[k][j] += board[i][j];
                        board[i][j] = 0;
						//分数增加
						score += board[k][j];
						updateScore(score); 
						hasConflicted[k][j]  = true;
						
                        continue;
                    }
                }
            }
        }

    setTimeout("updateBoardView()",200);
    return true;
}

function moveDown(){
    if( !canMoveDown( board ) )
        return false;

    //moveDown
    for( var j = 0 ; j < 4 ; j ++ )
        for( var i = 2 ; i >= 0 ; i -- ){
            if( board[i][j] != 0 ){
                for( var k = 3 ; k > i ; k -- ){

                    if( board[k][j] == 0 && noBlockVertical( j , i , k , board ) ){
                    	//移动
                        showMoveAnimation( i , j , k , j );
                        board[k][j] = board[i][j];
                        board[i][j] = 0;
                        continue;
                    }
                    else if( board[k][j] == board[i][j] && noBlockVertical( j , i , k , board )&& !hasConflicted[k][j] ){
                    	//移动
                        showMoveAnimation( i , j , k , j );
                        //增加
                        board[k][j] +=board[i][j];
                        board[i][j] = 0;
						//分数增加
						score += board[k][j];
						updateScore(score); 
						hasConflicted[k][j]  = true;
						
                        continue;
                    }
                }
            }
        }

    setTimeout("updateBoardView()",200);
    return true;
}